/**
 * This WebExtension grabs the URL of the page that is currently active, then
 * opens a new tab with the URL: https://web.archive.org/save/[URL]
 * 
 * --------------------------------------------------------------------------
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// This function does the actual archiving
function archive ()
{
    /**
     * Select the tab currently active.
     * Docs: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/Tabs/query
     */
    browser.tabs.query (
        { active: true },
        
        function (tabs) {
            if (!tabs || tabs.length != 1)
                return;
            
            // Get "autoswitch" option from local storage (switch to new tab?)
            browser.storage.local.get ('autoswitch', (option) => {
                
                /**
                 * Create a new tab with link to web.archive.org
                 * Docs: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/Tabs/create
                 */
                browser.tabs.create ({
                    url:    'https://web.archive.org/save/' + tabs[0].url,
                    active: option.autoswitch || false
                });
            });
        }
    );
}

/* Add context menu
 * Docs: https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/ContextMenus/create
 */
browser.contextMenus.create ({
    id:      'archive',
    title:   'Save page to Archive.org',
    onclick: function () { archive (); }
});

// Handler for toolbar icon click
browser.browserAction.onClicked.addListener (archive);

/**
 * Listen to command key (Ctrl+Period)
 * 
 * Docs:
 *   https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/commands
 *   https://dxr.mozilla.org/mozilla-central/source/browser/components/extensions/schemas/commands.json#14
 */
browser.commands.onCommand.addListener (function (command) {
    if ('archive' == command)
        archive ();
});